﻿using DefaultScope;
using Fabrikam.Client.DataModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using GalaSoft.MvvmLight.Messaging;
using Windows.Networking.Connectivity;

namespace Fabrikam.Client.ViewModels
{
    public class ItemsPageViewModel : ViewModelBase
    {
        private ObservableCollection<ServiceTicketViewModel> serviceTickets = new ObservableCollection<ServiceTicketViewModel>();
        private RelayCommand refreshCommand;
        private RelayCommand syncCommand;
        private RelayCommand<ServiceTickets> showTicketCommand;


        private RelayCommand addCommand;
        public RelayCommand AddCommand
        {
            get
            {
                if (addCommand != null) return addCommand;

                addCommand = new RelayCommand(async () =>
                {
                    SettingsFlyoutItem sf = new SettingsFlyoutItem();
                    Context.SettingFlyoutItemViewModel.InitServiceTicket(null);
                    sf.Width = 500;

                    var isComplete = await sf.ShowIndependentAsync();

                    if (isComplete)
                        this.RefreshCommand.Execute(null);

                });

                return addCommand;
            }
        }


        public ItemsPageViewModel()
        {
            if (IsInDesignMode)
                this.ServiceTickets = DataDesignerService.GetServiceTickets();
        }


        public RelayCommand RefreshCommand
        {
            get
            {
                if (refreshCommand != null) return refreshCommand;

                refreshCommand = new RelayCommand(async () =>
                {

                    if (DataService.Current.TableExist("ServiceTickets") == false)
                        return;

                   // return;
                    await GetServiceTickets();
                });

                return refreshCommand;
            }
        }

        public RelayCommand<ServiceTickets> ShowTicketCommand
        {
            get
            {
                if (showTicketCommand != null) return showTicketCommand;

                showTicketCommand = new RelayCommand<ServiceTickets>(async (st) =>
                {
                    var frame = ((Frame)Window.Current.Content);

                });

                return showTicketCommand;
            }
        }

        public RelayCommand SyncCommand
        {
            get
            {
                if (syncCommand != null) return syncCommand;

                syncCommand = new RelayCommand(async () =>
                {
                    try
                    {
                        this.IsSyncing = true;

                        var attenteTask = Task.Delay(1000);

                        var stats = await DataService.Current.Sync();

                        await attenteTask;

                        if (stats.Error != null)
                        {
                            var messageDialog = new MessageDialog("An error occured during sync session : " + Environment.NewLine + stats.Error.Message);
                            await messageDialog.ShowAsync();
                        }
                        else
                        {
                            if (stats.TotalDownloads > 0)
                                await GetServiceTickets();

                            var messageDialog = new MessageDialog(
                                "Sync session completed: " + Environment.NewLine +
                                "Total downloads :" + stats.TotalDownloads + Environment.NewLine +
                                "Total uploads   :" + stats.TotalUploads + Environment.NewLine +
                                "Total conflicts :" + stats.TotalSyncErrors + Environment.NewLine +
                                "Ellapsed Time   :" + stats.EndTime.Subtract(stats.StartTime).TotalSeconds + " s.");
                            await messageDialog.ShowAsync();

                        }

                        this.IsSyncing = false;

                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        throw;
                    }

                }, () =>
                {
                    var connectionIsOk = Context.Current.ConnectivityLevel == NetworkConnectivityLevel.InternetAccess;
                    var isNotSyncing = !this.IsSyncing;

                    return (connectionIsOk && isNotSyncing);

                });

                return syncCommand;
            }
        }


        private Boolean isSyncing;

        public Boolean IsSyncing
        {
            get
            {
                return isSyncing;
            }
            set
            {
                if (value == isSyncing)
                    return;

                isSyncing = value;

                base.RaisePropertyChanged(() => IsSyncing);
            }
        }


        private async Task GetServiceTickets()
        {
            ServiceTickets.Clear();

            var lst = await DataService.Current.GetTickets();

            foreach (var serviceTicket in lst)
                ServiceTickets.Add(new ServiceTicketViewModel(serviceTicket));

        }

        public ObservableCollection<ServiceTicketViewModel> ServiceTickets
        {
            get
            {
                return serviceTickets;
            }
            set
            {
                if (value == serviceTickets)
                    return;

                serviceTickets = value;

                base.RaisePropertyChanged(() => ServiceTickets);
            }
        }


    }
}
